import React, { useEffect, useRef, useState } from 'react'
import { Layout, Menu, Button, Avatar } from 'antd'
import { Link, Outlet, useLocation } from 'react-router-dom'
import { ParallaxProvider } from 'react-scroll-parallax'
import AOS from 'aos'
import 'aos/dist/aos.css'
import './layout.less'

const { Header, Content, Footer } = Layout

const HEADER_HEIGHT = 64

const MainLayout: React.FC = () => {
  const location = useLocation()
  const currentPath = location.pathname
  const aboutRef = useRef<HTMLDivElement>(null)

  const [isNavVisible, setIsNavVisible] = useState(true)
  const prevScrollYRef = useRef<number>(0)

  useEffect(() => {
    AOS.init({
      duration: 800,
      once: false,
      mirror: true,
    })

    prevScrollYRef.current = window.scrollY

    const handleScroll = () => {
      const current = window.scrollY
      const prev = prevScrollYRef.current

      if (current > prev) {
        // 向下滚动 -> 隐藏
        setIsNavVisible((prevVisible) => (prevVisible ? false : prevVisible))
      } else if (current < prev) {
        // 向上滚动 -> 显示
        setIsNavVisible((prevVisible) => (prevVisible ? prevVisible : true))
      }

      prevScrollYRef.current = current
    }

    window.addEventListener('scroll', handleScroll, { passive: true })
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  // 路由变化时恢复显示
  useEffect(() => {
    setIsNavVisible(true)
  }, [currentPath])

  const scrollToAbout = (e: React.MouseEvent) => {
    e.preventDefault()
    if (aboutRef.current) {
      aboutRef.current.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      })
    }
  }

  const menuItems = [
    { key: '/', label: '首页' },
    { key: '/employment', label: '就业去向' },
    { key: '/team', label: '团队成员' },
    { key: '/articles', label: '优质文章' },
    { key: '/contact', label: '联系我们' },
    { key: '/demo', label: '性能监测' },
  ]

  return (
    <ParallaxProvider>
      <Layout className='layout'>
        <Header
          className={`header ${isNavVisible ? 'visible' : 'hidden'}`}
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            zIndex: 1000,
            width: '100%',
            height: HEADER_HEIGHT,
            transition: 'transform 0.28s ease, opacity 0.28s ease',
            willChange: 'transform, opacity',
            opacity: isNavVisible ? 1 : 0,
            transform: isNavVisible ? 'translateY(0)' : 'translateY(-100%)',
          }}
        >
          <div className='logo-container'>
            <Avatar
              size={40}
              className='logo-avatar'
              src='/public/实验室头像.jpg'
            />
            <div className='logo'>西邮EPI软件实验室</div>
          </div>
          <Menu
            theme='dark'
            mode='horizontal'
            selectedKeys={[
              currentPath === '/' ? '/' : `/${currentPath.split('/')[1]}`,
            ]}
            items={menuItems.map((item) => ({
              key: item.key,
              label: <Link to={item.key}>{item.label}</Link>,
            }))}
          />
          <Button
            type='primary'
            className='join-button'
            shape='round'
            size='large'
          >
            <Link to='/join'>加入我们</Link>
          </Button>
        </Header>

        <Content className='content' style={{ paddingTop: HEADER_HEIGHT }}>
          <div className='content-container'>
            <Outlet context={{ aboutRef }} />
          </div>
        </Content>

        <Footer className='footer'>
          <div className='footer-content'>
            <div className='footer-links'>
              <a href='#' onClick={scrollToAbout}>
                关于我们
              </a>
            </div>
            <div className='footer-copyright'>
              西邮EPI软件实验室 ©{new Date().getFullYear()} Created by Lab Team
            </div>
            <div className='footer-social'>
              <a
                href='https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzkxNDU2OTk2NA==&scene=124#wechat_redirect'
                className='social-icon'
              >
                公众号
              </a>
              <a
                href='https://xuptflying.github.io/xupt-flying.github.io/#/'
                className='social-icon'
              >
                飞跃手册
              </a>
              <a href='https://github.com/EpiHome' className='social-icon'>
                GitHub
              </a>
            </div>
          </div>
        </Footer>
      </Layout>
    </ParallaxProvider>
  )
}

export default MainLayout
